package com.nbicc.attachments.controller;

import com.nbicc.attachments.po.Attachment;
import com.nbicc.attachments.service.IAttachmentService;
import com.nbicc.common.ResponseObj;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(value = "附件" , description = "附件实体的操作")
@RestController
@RequestMapping(value = "/attachment")
public class AttachmentController {

    @Resource(name = "AttachmentServiceImpl")
    private IAttachmentService attachmentService;

    @ApiOperation(value = "附件上传" , notes = "完成后 返回附件元数据")
    @PostMapping
    public ResponseObj uploadFile(
            HttpServletRequest request,
            MultipartFile uploadFile) throws Exception {
        Attachment attachment = attachmentService.uploadFile(request, uploadFile);
        return ResponseObj.success().setResult(attachment);
    }

    @ApiOperation(value = "附件下载" , notes = "提供附件id即可下载")
    @GetMapping("/{id}")
    public void downloadFile(
            @PathVariable("id") long id,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        attachmentService.downloadFile(request , response , id);
    }

    @ApiOperation(value = "附件删除" , notes = "需附件id")
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseObj deleteFile(@PathVariable long id) throws IOException {
        attachmentService.deleteFile(id);
        return ResponseObj.success();
    }

}
